import axios from "axios";
import {ElMessage} from "element-plus";
import route from "@/router";

// 创建axios实例
const request = axios.create({
    baseURL: '/api', // api 的 base_url
    timeout: 5000, // 请求超时时间
});

// request拦截器
request.interceptors.request.use(
    (config) => {
        const loginUser = JSON.parse(localStorage.getItem('loginUser'));
        // 设置token
        if (loginUser && loginUser.token) {
            config.headers.token = loginUser.token;
        }
        return config;
    },
    (error) => {
        console.log("request error", error);
        return Promise.reject(error);
    }
);

// response 拦截器
request.interceptors.response.use(
    (response) => {
        if (response.status) {
            return Promise.resolve(response.data);
        } else {
            return Promise.reject(response);
        }
    },
    (error) => {
        if (error.response.status === 401) {
            localStorage.removeItem('loginUser');
            route.push('/login');
            ElMessage.error("登录状态失效，请重新登录");
        }
        ElMessage.error(error.message);
        return Promise.reject(error);
    }
);

export default request;
